var app = getApp();
var custId = app.globalData.custID;
var common = require("../../utils/Conmon.js");
Page({

  /**
   * 页面的初始数据
   */
  data: {
    index: 0,
    array: ['不限收货时间', '只限工作日收货', '共组日/双休日/节假日均可收货', '只限双休日收货'],
    cartList: [],
    cneeId: 0,
    list: [],
    freightMoney: '免邮',
    cartMoney: 0,
    addr: null,
    remark: "",
    remarkList: [],
    pointName: "",
    deductiblePoint: 0,  //可抵扣总积分
    bili: 0,
    totalIntegral: "",
    totalCommission: "",
    showCartMoney:'0.00'
  },

  bindPickerChange: function (e) {
    this.setData({
      index: e.detail.value
    })
  },
  //备注
  bindRemark: function (e) {
    var rlist = this.data.remarkList;
    var content = e.detail.value;
    var shopId = e.target.dataset.shopid;
    for (var i = 0, len = rlist.length; i < len; i++) {
      if (rlist[i].ShopId == shopId) {
        rlist[i].Remark = content;
      }
    }
    this.setData({
      remarkList: rlist
    });
  },
  //抵扣积分计算
  deductibleCalculate: function (e) {
    var shopId = e.target.dataset.shopid;
    var sumMoney = parseFloat(this.data.cartMoney);
    var remainPoint = this.data.deductiblePoint;
    var list = this.data.list;
    var bili = this.data.bili;
    var usePoint = 0;
    var maxindex = 1;

    var selfck = false;  //自己的状态
    for (var i = 0, len = list.length; i < len; i++) {
      if (list[i].ShopId == shopId) {
        list[i].checked = !list[i].checked;
        selfck = list[i].checked;
        break;
      }
    }
    this.setData({
      list: list
    });

    for (var i = 0, len = list.length; i < len; i++) {
      var dikou = 0;
      var cartMoney = list[i].CartMoney;
      if (!selfck || list[i].ShopId != shopId) {
        if (list[i].checked) {
          if (cartMoney > 0 && remainPoint > 0) {
            var re = remainPoint - cartMoney;
            if (re > 0) {
              dikou = cartMoney;
              cartMoney = 0;
              remainPoint = re;
            } else {
              dikou = remainPoint;
              cartMoney = cartMoney - remainPoint;
              remainPoint = 0;
            }
            list[i].checked = true;
            list[i].indexnum = maxindex;
            maxindex = maxindex + 1;
          } else {
            list[i].checked = false;
            list[i].indexnum = 0;
          }
        } else {
          dikou = 0;
          list[i].checked = false;
          list[i].indexnum = 0;
        }
        usePoint += dikou;
        list[i].showCartMoney = cartMoney;
        list[i].dikou = dikou * bili;
        list[i].deductibleMoney = dikou;
      }
    }

    for (var i = 0, len = list.length; i < len; i++) {
      if (list[i].ShopId == shopId && list[i].checked) {        
        var dikou = 0;
        var cartMoney = list[i].CartMoney;
        if (cartMoney > 0 && remainPoint > 0) {
          var re = remainPoint - cartMoney;
          if (re > 0) {
            dikou = cartMoney;
            cartMoney = 0;
            remainPoint = re;
          } else {
            dikou = remainPoint;
            cartMoney = cartMoney - remainPoint;
            remainPoint = 0;
          }
          list[i].indexnum = maxindex;
          list[i].checked = true;
        } else {
          list[i].indexnum = 0;
          list[i].checked = false;
          wx.showModal({
            content: "已达到最大抵扣金额",
            showCancel: false,
            confirmText: "确定"
          })
        }
        usePoint += dikou;
        list[i].showCartMoney = cartMoney;
        list[i].dikou = dikou * bili;
        list[i].deductibleMoney = dikou;
        break;    
      }
    }

    var final = sumMoney - usePoint;
    this.setData({
      list: list,
      showCartMoney: final
    });
  },

  //下单
  goSubmit: function (e) {
    var that = this;
    if (that.data.cneeId == 0 || that.data.cneeId == undefined) {
      wx.showModal({
        content: "请选择收货地址",
        showCancel: false,
        confirmText: "确定"
      });
      return;
    }
    //抵扣
    var list = that.data.list;
    var deductiblelist = [];
    for (var i = 0, len = list.length; i < len; i++) {
      if (list[i].checked) {
        var deductible = {};
        deductible.ShopId = list[i].ShopId;
        deductible.Index = list[i].indexnum;
        deductiblelist.push(deductible);
      }
    }

    wx.showLoading({
      title: '加载中...',
      mask: true
    });
    var data =
      {
        CustId: custId,
        UserId: wx.getStorageSync('UserInfo').UserID,
        CneeId: that.data.cneeId,
        RemarkList: that.data.remarkList,
        SelectCartList: that.data.cartList,
        DeductibleList: deductiblelist
      };
    wx.request({
      url: app.globalData.apiurl + '/mobile/api/OrderForm/OrderWechat',
      data: JSON.stringify(data),
      method: 'POST',
      header: {
        'X_ManuName': app.globalData.manuName
      },
      success: function (res) {
        wx.hideLoading();
        if (res.data.code == 1200) {
          var orderId = res.data.content.OrderID;
          var payno = res.data.content.PayNo;
          //清除缓存
          wx.removeStorageSync('Winmobi4MallSelectedShopCart');
          wx.redirectTo({
            url: '/pages/submitOrder2/submitOrder2?PayNo=' + payno,
          })
        } else if (res.data.code == 200){
          wx.removeStorageSync('Winmobi4MallSelectedShopCart');
          wx.showModal({
            content: '支付成功',
            showCancel: false,
            confirmText: "确定",
            success: function (res) {
              if (res.confirm) {
                wx.switchTab({
                  url: '/pages/myorders/myorders',
                });
              }
            }
          });          
        } else {
          wx.showModal({
            content: res.data.msg,
            showCancel: false,
            confirmText: "确定"
          })
        }
      }
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    //获取缓存的购物车选中项
    console.log(1123);
    var cartList = wx.getStorageSync('Winmobi4MallSelectedShopCart');
    if (cartList == null || cartList.length <= 0) {
      wx.showModal({
        content: "请先选择要购买的商品",
        showCancel: false,
        confirmText: "确定",
        complete: function () {
          wx.switchTab({
            url: '/pages/cart/cart'
          })
        }
      })
    }
    this.setData({
      cartList: cartList,
      cneeId: options.CneeID
    });
    //加载数据
    loadCartProduct(this);
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})

function loadCartProduct(that) {
  if (that.data.cartList == null || that.data.cartList.length <= 0) {
    wx.showModal({
      content: "请先选择要购买的商品",
      showCancel: false,
      confirmText: "确定",
      complete: function () {
        wx.switchTab({
          url: '/pages/cart/cart'
        })
      }
    })
  }

  wx.showLoading({
    title: '加载中...',
    mask: true
  });
  var data = { CustId: custId, UserId: wx.getStorageSync('UserInfo').UserID, SelectCartList: that.data.cartList, CneeId: that.data.cneeId };
  wx.request({
    url: app.globalData.apiurl + '/mobile/api/OrderForm/GetSelectCartProductListWechat',
    data: JSON.stringify(data),
    method: 'POST',
    header: {
      'X_ManuName': app.globalData.manuName
    },
    success: function (res) {
      wx.hideLoading();
      if (res.data.code == 1200) {
        var result = res.data.content;
        var cnee = result.CneeAddress;
        if (cnee) {
          that.setData({
            cneeId: cnee.CneeID
          });
        }
        var rlist = [];
        // var deductlist = [];
        if (result.UnionCartProducts) {
          for (var i = 0, len = result.UnionCartProducts.length; i < len; i++) {
            var shop = {};
            shop.ShopId = result.UnionCartProducts[i].ShopId;
            shop.Remark = "";
            rlist.push(shop);

            result.UnionCartProducts[i].checked = false;
            result.UnionCartProducts[i].indexnum = 0;
            result.UnionCartProducts[i].dikou = 0;
            result.UnionCartProducts[i].deductibleMoney = 0;
            result.UnionCartProducts[i].showCartMoney = result.UnionCartProducts[i].CartMoney;
          }
        }
        that.setData({
          list: result.UnionCartProducts,
          cartMoney: result.CartMoney.toFixed(2),
          addr: result.CneeAddress,
          remarkList: rlist,
          pointName: result.PointName,
          deductiblePoint: parseFloat(result.DeductiblePoint),
          bili: parseFloat(result.Bili),
          totalIntegral: result.TotalIntegral,
          totalCommission: result.TotalCommission,
          showCartMoney: result.CartMoney.toFixed(2),
        });
      } else {
        console.log('加载失败');
      }
    }
  })
}
